<template>
  <eui-background type="common">
    <eui-navbar ref="RdsNavBar" :title="inputData.main.c_id" status-bar="true" :closeCallback="closeCallback">
      <template v-slot:titleExpand>
        <text v-if="inputData.main">{{ sysConfig.c_step[inputData.main.c_step] }}</text>
      </template>
      <template v-slot:popupContent>
        <view class="custom-box">
          <view class="custom-menu" v-show="false">
            <view class="setting-item">
              <eui-card-input
                  v-model="defaultShelfNo"
                  ref="defaultShelfNoInput"
                  title="默认货架"
                  placeholder="请扫货架编号"
                  scan="scan"
                  :rifhtIcon="true"
                  @clickRightScan="clickScanRight('defaultShelfNo')"
                  isBlur
                  @confirm="changeDefaultShelfNo"
                  @blur="changeDefaultShelfNo"
              ></eui-card-input>
            </view>
          </view>
          <view class="custom-menu">
            <eui-card-input
                type="radio"
                title="计数方式:"
                alignType="left"
                v-model="overwriteMode[0].value"
                @buttonClick="toggleOverwriteMode"
                :range="overwriteModeDict"
            />
          </view>
          <view class="custom-menu">
            <eui-card-input
                type="radio"
                title="录入方式:"
                alignType="left"
                v-model="inputMode[0].value"
                @buttonClick="toggleModeRadio"
                :range="sysConfig.c_input_mode"
                :disabled="sysConfig.enableInputMode == 0"
            />
          </view>
          <view class="custom-menu">
            <view class="setting-item" v-if="inputMode.length > 0 && ['3'].includes(inputMode[0].value)">
              <eui-text
                  type="name"
                  value=""
                  title="说明: 【件数+细数】: 细数采用累计模式，大于含量不覆盖件数，盘点实物时，细数有可能超过含量。比如：牛奶一箱12盒，拆零了两箱，目前盘点时，细数是18，件数是5，则盘点数量是78；"
              />
            </view>
            <view class="setting-item" v-if="inputMode.length > 0 && ['4'].includes(inputMode[0].value)">
              <eui-text type="name" value="" title="说明: 【见物扫物】: 逐个扫描商品条码，数量累加"/>
            </view>
          </view>
          <view class="custom-menu">
            <view class="setting-item" v-if="inputMode.length > 0 && ['4'].includes(inputMode[0].value)">
              <eui-text type="name" title="【见物扫物】: 数量是否自动累加"/>
              <eui-card-input v-model="isAutoAdd" @change="toggleAutoAdd"
                              type="switch"></eui-card-input>
            </view>
          </view>
        </view>
      </template>
    </eui-navbar>
    <view class="search_view">
      <eui-search-bar
          class="search_sno"
          v-model="defaultShelfNo"
          ref="RdsSearchShelfNo"
          placeholder="请扫货架编号"
          :show-filter-icon="false"
          :autoFocus="false"
          leftIcon="icon-saoyisao"
          @leftIconClick="()=>clickScanRight('defaultShelfNo')"
          radius="30"
          @confirm="changeDefaultShelfNo"
          isBlur
          @blur="changeDefaultShelfNo"
      />
      <eui-search-bar
          v-model="searchText"
          :focus="true"
          style="flex: 1 0 0"
          ref="RdsSearchBar"
          placeholder="请扫商品条码"
          @confirm="searchConfirm"
          :show-filter-icon="false"
          leftIcon="icon-saoyisao"
          @leftIconClick="()=>clickScanRight('defaultBarcode')"
          radius="30"
      />
    </view>
    <view class="count_input_view">
      <view class="count_input_column column_title">
        <eui-card-input v-model="currentGds.c_gname" type="text" :titleWidth="0" placeholder="" displayable/>
      </view>
      <view class="count_input_column count_input_num">
        <eui-card-input style="flex-grow:2;" :value="currentGdsCode" title="条码" type="text" placeholder=""
                        displayable/>
        <eui-card-input style="flex-grow:1;" :value="currentGdsUnit" title="包装" type="text" placeholder=""
                        displayable/>
      </view>
      <view class="count_input_column count_input_num">
        <eui-card-input
            style="flex-grow:1;"
            :displayable="!currentGds.c_gcode || !(inputMode.length > 0 && !['1', '4'].includes(inputModeValue))"
            v-model="currentGds.c_n_pack"
            ref="gdsNumPackInput"
            type="number2"
            title="件数"
            placeholder=""
            isBlur
            @confirm="inputNumConfirm"
            :clearable="true"
            maxlength="9"
            id="c_n_pack"
        />
        <eui-card-input
            style="flex-grow:1;"
            :displayable="!currentGds.c_gcode || !(Number(currentGds.c_pack) > 1 && ['3'].includes(inputModeValue))"
            v-model="currentGds.c_n_odd"
            ref="gdsUnitInput"
            type="number2"
            title="细数"
            placeholder=""
            isBlur
            @confirm="inputNumConfirm"
            :clearable="true"
            maxlength="9"
            id="c_n_odd"
        />
        <eui-card-input
            style="flex-grow:1;"
            :displayable=" !currentGds.c_gcode || !(inputMode.length > 0 && ['1', '4'].includes(inputModeValue))"
            v-model="currentGds.c_n"
            ref="gdsNumInput"
            type="digit"
            title="数量"
            placeholder=""
            isBlur
            @confirm="inputNumConfirm"
            :clearable="true"
            maxlength="9"
            id="c_n"
        />
      </view>
    </view>
    <view class="virtual_head">
<!--      <text class="cell_color_code" style="flex: 0 0 19%">序号</text>-->
      <text class="cell_color_code" style="flex: 0 0 20%">货架</text>
      <text class="cell_color_code" style="flex: 0 0 60%">商品(编码/条码)</text>
      <text class="cell_color_code cell_color_num flex_w_auto">实盘数量</text>
    </view>
    <view class="footer-view" :style="{ height: listHeight + 'rpx' }">
      <eui-virtual-list :showIndex="true" type="list2" v-if="isToggle" :origList="dataListReverse" keyId="c_gsort">
        <template v-slot:list="scope">
<!--          <view class="list_cell_item cell_color_id" style="flex: 0 0 20%">{{ scope.c_gsort }}</view>-->
          <view class="list_cell_item cell_color_code" style="flex: 0 0 20%">
            <view>{{ scope.c_shelf_no }}</view>
            <view class="cell_color_code2">{{ scope.c_gsort }}</view>
          </view>
          <view class="list_cell_item" style="flex: 0 0 60%">
            <view>{{ scope.c_gname }}</view>
            <view class="cell_color_code">{{ scope.c_gcode }}/{{ scope.c_barcode }}</view>
          </view>
          <view class="list_cell_item cell_color_num flex_w_auto">{{ scope.c_n }}</view>
        </template>
      </eui-virtual-list>
      <eui-virtual-list  :showIndex="true" type="list2" v-if="!isToggle" :origList="inputData.details">
        <template v-slot:list="scope">
<!--          <view class="list_cell_item cell_color_id" style="flex: 0 0 20%">{{ scope.c_gsort }}</view>-->
          <view class="list_cell_item cell_color_code" style="flex: 0 0 20%">
            <view>{{ scope.c_shelf_no }}</view>
            <view class="cell_color_code2">{{ scope.c_gsort }}</view>
          </view>
          <view class="list_cell_item" style="flex: 0 0 60%">
            <view>{{ scope.c_gname }}</view>
            <view class="cell_color_code">{{ scope.c_gcode }}/{{ scope.c_barcode }}</view>
          </view>
          <view class="list_cell_item cell_color_num flex_w_auto">{{ scope.c_n }}</view>
        </template>
      </eui-virtual-list>
    </view>
    <view class="virtual_footer">
      <text class="cell_color_code" style="flex: 0 0 50%">总计 {{ total_line }} 行</text>
      <text class="cell_color_code cell_color_num flex_w_auto">数量总计：{{ total_num }}</text>
    </view>
    <view class="bottom-view">
      <view class="center-style">
        <eui-button
            type="max2"
            singleTag="default"
            :title="btnText"
            @buttonClick="buttonClick"
        />
        <view class="gap-view"/>
        <eui-button
            type="max"
            singleTag="save"
            title="保存"
            @buttonClick="buttonClick"
            v-if="inputData.main && inputData.main.c_status == '0'"
            :disabled="!(dataList.length > 0 && btnSaveEnabled)"
        />
      </view>
    </view>
  </eui-background>
</template>

<script setup type="ts">
import service from '@/common/service';
import { getRdsSysConfig } from '@/hooks/init';
import {getRdsUrl, rdsRequest, rdsRequestAsync} from '@/hooks/rdsServices';
import { onBackPress, onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref } from 'vue';
import dateRangUtil from '../../../common/dateRangUtil';
import { useMainStore } from '../../../store/modules/store';
import { useLoginStore } from '../../../store/modules/useLoginStore';
import { getDictList, getWeightUnits } from '../components/RelatedName';

const rdsUrl = getRdsUrl();
const c_id = ref(''); // 标题栏显示单号
const dataList = ref([]); // 当前录入的商品列表
const c_id_ref = ref('');
const overwriteMode = ref([{
  text: '分行累加',
  value: '0'
}]);
const overwriteModeDict = ref([{
  text: '分行累加',
  value: '0'
},{
  text: '覆盖',
  value: '1'
}]); // “累加” 0 or "覆盖" 1,默认覆盖 1
// 盘点单主+明细
const origData = ref({
  main: {},
  details: [],
});

// 录入单主+明细
const inputData = ref({
  main: {},
  details: [],
});

// 系统参数，字典
const sysConfig = ref({
  c_step: {},       // 盘点类型
  c_status: {},     // 单据状态
  c_input_mode: [], // 盘点录入方式
  enableInputMode: 1, // 是否允许修改录入方式
});

// 重量单位范围：用于验证商品数量是否可以录入小数
const weightUnits = ref([]);

// 当前扫描到的商品
const currentGds = ref({
  c_gcode: '',
  c_gname: '',
  c_pack: '',
  c_unit: '',
  c_mk_userno: '',
  c_mk_dev: '',
  c_n_pack: null,
  c_n_odd: null,
  c_n: null
});
// 计数方式为累加时 使用 扫描商品的副本
const currentGdsOrig = ref({
  c_gcode: '',
  c_gname: '',
  c_pack: '',
  c_unit: '',
  c_mk_userno: '',
  c_mk_dev: '',
  c_n_pack: null,
  c_n_odd: null,
  c_n: null
});

// 当前扫描到的商品存在于哪个列表
// currentGdsPosition:   0: dataList,  1: inputData.details， 2: inputData.details 但不匹配货架, 3:  多条码商品
const currentGdsPosition = ref(-1);

// 录入方式 是否连续扫描模式
const isScan = ref(true);

// 录入方式 1-数量、2-件数、3-件数+细数 (细数采用累计模式，大于含量时不覆盖件数)、4-见物扫物（逐个扫描商品条码，数量累加）
const inputMode = ref([{
  text:'数量',
  value: '1'
}]);

// 称重商品自动切换录入方式前的录入方式
const inputModeOrig = ref([])

// 是否在连扫模式下商品数量自动+1
const isAutoAdd = ref(true);

// 默认货架
const defaultShelfNo = ref('无货架');
const searchText = ref('');

// 默认显示录入列表，false 显示原始列表
const isToggle = ref(true);

// 当前录入单最大序号
const gsort = ref(0);

// 多条码商品列表（区分不同的包装含量）
const barcodeList = ref([]);

// 其他变量
const mySortMin = ref(0);
const mySortMax = ref(0);
const myInputSort = ref([]);
const btnSaveEnabled = ref(true);

// 聚焦
const gdsUnitInput = ref(null);
const RdsSearchBar = ref(null);
const gdsNumInput = ref(null);
const gdsNumPackInput = ref(null);

const mainStore = useMainStore();
const LoginStore = useLoginStore();
const listHeight = ref(300)

// 是否可以退出（未保存数据）
const canExit = ref(true)

// 计算属性
const isAddNew = computed(() => currentGds.value.c_gdscode !== undefined);

const inputModeValue = computed(() =>
    inputMode?.value[0]?.value || ''
);

const currentGdsCode = computed(() =>
    currentGds.value.c_gcode !== '' ? `${currentGds.value.c_gcode}/${currentGds.value.c_barcode}` : '',
);

const currentGdsUnit = computed(() =>
    currentGds.value.c_gcode !== '' ? `${currentGds.value.c_pack}/${currentGds.value.c_unit}` : '',
);

const btnText = computed(() => (isToggle.value ? '显示全部商品' : '显示录入商品'));

const total_line = computed(() =>
    isToggle.value ? dataList.value.length : inputData.value.details.length,
);

const total_num = computed(() => {
  let total;
  if (isToggle.value) {
    total = dataList.value.reduce((sum, item) => sum + Number(item.c_n), 0);
  } else {
    total = inputData.value.details.reduce((sum, item) => sum + Number(item.c_n), 0);
  }
  return Math.round(total * 1000) / 1000;
});

const dataListReverse = computed(()=> [...dataList.value].reverse());

// 生命周期钩子
onLoad(async ({c_id: c_id_param, c_gcode, c_store_id, pid, showDetails}) => {
  service.enjoyShowLoading('正在加载...');
  await getSysConfig();
  if (!pid) {
    await getData(c_id_param);
    await getInputList(c_id_param, c_store_id);
  } else {
    await getInputData(pid);
    // 过滤当前用户数据
    dataList.value = inputData.value.details.filter(item => {
      return item.c_mk_userno == mainStore.loginInfo.sUser
    })
  }
  if (showDetails === 'true') {
    changeToggle()
  }
  // 切换录入模式
  toggleMode(
      sysConfig.value.c_input_mode.filter(
          (item) => item.value == (inputData.value.main.c_input_mode || origData.value.main.c_input_mode),
      ),
  );
  service.enjoyHideLoading();
  onfocusGds();
});

// 监听返回事件 onBackPress
// return true 表示禁止返回
// return false 表示返回
onBackPress((event) => {
  if (!canExit.value) {
    uni.showModal({
      title: '提示',
      content: '数据尚未保存，是否保存？',
      cancelText: '不保存',
      confirmText: '保存',
      success: async (res) => {
        if (res.confirm) {
          await saveCountInput();
          // 确定保存返回
          uni.navigateBack({
            delta: 1
          });
        } else if (res.cancel) {
          // 不保存返回
          canExit.value = true;
          uni.navigateBack({
            delta: 1
          });
        }
      },
    });
    return true;
  }
  return false;
})
;

onMounted(() => {
  getListHeight();
});

// MARK: - 方法定义
// 获取列表高度
const getListHeight = async () => {
  await uni.getSystemInfo({
    success: function (res) { // res - 各种参数
      let info = uni.createSelectorQuery().select(".footer-view");
      info.boundingClientRect(function (data) { //data - 各种参数
        //获取列表高度
        let height = res.windowHeight - data.top;
        //转换rpx
        listHeight.value = height / (res.windowWidth / 750) - 200;
      }).exec()
    }
  });
};
// 扫描条形码
const openBarcode = (name) => {
  uni.scanCode({
    success: function (res) {
      if (res.result) {
        // 处理扫描结果，例如：
        // currentGds.value[name] = res.result;
        // GetOutLoadDetail();
      }
    },
  });
};

// 列表项样式，区分当前扫描到的商品
const dataListClass = (item) => {
  if (
      item.c_barcode === currentGds.value.c_barcode &&
      item.c_shelf_no === currentGds.value.c_shelf_no
  ) {
    return `rds-count-input-content with-current-gds`;
  } else {
    return `rds-count-input-content`;
  }
};
// 等待300
function wait300ms() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, 300);
  });
}
// 数量输入框确认后控制聚焦
const inputNumConfirm = async () => {
  await wait300ms(); // 等待 300 毫秒
  const hasNum = checkInputNum();
  if (!hasNum)  {
    RdsSearchBar?.value.clear();
    return false
  };
  const {_key, c_gsort, c_n, c_n_pack, c_n_odd, c_pack } = currentGds.value;
  let new_gsort = gsort.value
  // if (c_gsort > mySortMin.value && c_gsort <= mySortMax.value) {
  //   new_gsort = c_gsort
  // }
  // 计数方式选择 overwriteMode[0].value
  // “分行累加” 0 or "覆盖" 1,默认覆盖 1
  let new_c_n = c_n;
  let new_c_n_pack = c_n_pack;
  let new_c_n_odd = c_n_odd
  if (overwriteMode.value[0].value == '0') {
    // 分行
    currentGdsPosition.value = 3;
    // if ( gsort.value === mySortMin.value + 1 ) {
    //   // 忽略第一次添加
    // } else {
    //   new_gsort += 1;
    // }
  }

  // 多包装商品及件数聚焦条件的判断
  const isPackMode =  gdsNumPackInput.value.c_focus && inputModeValue.value === '3' && c_pack > 1;
  const isNotNull = new_c_n != 0 && new_c_n != '' && new_c_n != null;

  // 更新到保存列表
  if (currentGdsPosition.value === 0 && isNotNull  && !isPackMode) {
    dataList.value.splice(_key, 1, {
      ...currentGds.value,
      c_n: new_c_n,
      c_n_pack: new_c_n_pack,
      c_n_odd: new_c_n_odd
    });
  }
  // 新增到保存列表
  // currentGdsPosition:   0: dataList,  1: inputData.details， 2: inputData.details 但不匹配货架, 3:  多条码商品
  if (currentGdsPosition.value === 1 && isNotNull && !isPackMode) {
    dataList.value.push({
      ...currentGds.value,
      _key: dataList.value.length,
      c_gsort: new_gsort,
      c_n: new_c_n,
      c_n_pack: new_c_n_pack,
      c_n_odd: new_c_n_odd
    });
    currentGds.value = {
      ...currentGds.value,
      _key: dataList.value.length - 1,
    };
  }
  if (currentGdsPosition.value === 2 && isNotNull && !isPackMode) {
    dataList.value.push({
      ...currentGds.value,
      c_shelf_no: defaultShelfNo.value,
      c_gsort: new_gsort,
      c_count_gsort: new_gsort,
      _key: dataList.value.length,
      c_n: new_c_n,
      c_n_pack: new_c_n_pack,
      c_n_odd: new_c_n_odd
    });
    currentGds.value = {
      ...currentGds.value,
      c_gsort: new_gsort,
      c_count_gsort: new_gsort,
      _key: dataList.value.length - 1,
    };
  }
  if (currentGdsPosition.value === 3 && isNotNull && !isPackMode) {
    dataList.value.push({
      ...currentGds.value,
      c_shelf_no: defaultShelfNo.value,
      c_gsort: new_gsort,
      c_count_gsort: new_gsort,
      _key: dataList.value.length,
      c_n: new_c_n,
      c_n_pack: new_c_n_pack,
      c_n_odd: new_c_n_odd
    });
    currentGds.value = {
      ...currentGds.value,
      c_shelf_no: defaultShelfNo.value,
      c_gsort: new_gsort,
      c_count_gsort: new_gsort,
      _key: dataList.value.length - 1,
    };
  }

  //
  currentGdsPosition.value = 0;

  // 自动保存
  // await saveCountInput();

  // 当前模式未件数+细数且光标聚焦在件数上时不清空
  if (!isPackMode) {
    // 清空当前商品
    currentGds.value = {
      c_gcode: '',
      c_gname: '',
      c_pack: '',
      c_unit: '',
      c_mk_userno: '',
      c_mk_dev: '',
      c_n_pack: null,
      c_n_odd: null,
      c_n: null
    }
    // 计数+1
    gsort.value += 1;
  }

  // 控制聚焦
  if (isPackMode) {
    gdsUnitInput.value.getFocus();
  } else {
    onfocusGds();
  }

  // 标识未保存
  canExit.value = false;
};

// 输入检查
const checkInputNum = () => {
  const {c_n_pack, c_n_odd, c_pack, c_n, c_unit, c_plu_type, c_gcode} = currentGds.value;
  if (c_gcode == '') return false
  let new_c_n = Number(c_n)|| null;
  let new_c_n_pack = null;
  let new_c_n_odd = null;
  // 根据录入方式计算数量 1-数量、2-件数、3-件数+细数、4-见物扫物
  if (inputModeValue.value === '1') {
    new_c_n = Number(c_n) || null;
  }
  if (inputModeValue.value === '2') {
    new_c_n_pack = Math.floor(Number(c_n_pack)) || null;
    new_c_n = Number(c_n_pack) * Number(c_pack || 1) || null;
  }
  if (inputModeValue.value === '3') {
    new_c_n_pack = Math.floor(Number(c_n_pack)) || null;
    new_c_n_odd = Math.floor(Number(c_n_odd)) || null;
    new_c_n = Number(c_n_pack) * Number(c_pack || 1) + Number(c_n_odd) || null;
  }

  // 分行累加方式下 且 见物扫物模式，且设置了自动累加时
  if (overwriteMode.value[0].value == '0' && isScan.value === true && isAutoAdd.value === true) {
    new_c_n = Number(c_pack || 1) == 1 ? 1 : 1 * c_pack;
  }

  // 根据商品 称重/计件类型 c_plu_type === 1 称重PLU, 转换小数
  if (c_plu_type === '1') {
    new_c_n = parseFloat(new_c_n?.toFixed(3)) || null
  } else {
    new_c_n =Math.floor(new_c_n) || null;
  }

  // 重置数据
  currentGds.value = {
    ...currentGds.value,
    c_n: new_c_n,
    c_n_pack: new_c_n_pack,
    c_n_odd: new_c_n_odd,
  };
  // 多包装商品及件数聚焦条件的判断
  const isPackMode =  gdsNumPackInput.value.c_focus && inputModeValue.value === '3' && c_pack > 1;

  if ((new_c_n == 0 || new_c_n == '' || new_c_n == null) && !isPackMode) {
    // 弹窗提示, 排查“件数+细数”方式且当前录入框聚焦在“件数”的时刻
    uni.showToast({
      duration: 1000,
      icon: 'none',
      title: '数量不能为空或等于0!',
      mask: true
    });
    // 清空当前商品
    currentGds.value = {
      c_gcode: '',
      c_gname: '',
      c_pack: '',
      c_unit: '',
      c_mk_userno: '',
      c_mk_dev: '',
      c_n_pack: null,
      c_n_odd: null,
      c_n: null
    }
    return false
  };
  return true;
};

// 页面回调方法
const searchConfirm = async (code) => {
  let e = code.value.trim();
  if (e === '') {
    onfocusGds();
    return;
  }
  searchText.value = e;
  const {loginInfo} = mainStore;
  const {sUser} = loginInfo;

  const serialInfo = {
    gcode: e,
    serialNo: '',
    sda: null,
    eda: null,
  };

  const valSerialRes = await rdsRequestAsync(
      rdsUrl.scApi,
      'Rds公共服务',
      'ValiSerialNoRule',
      {storeId: inputData.value.main.c_store_id, serialNo: e},
  );

  if (valSerialRes.HasException) {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: valSerialRes.Exception.Message,
      mask: true,
    });
    return;
  } else {
    if (valSerialRes.ObjectData?.isMatchRule) {
      e = valSerialRes.ObjectData.gcode;
      serialInfo.gcode = valSerialRes.ObjectData.gcode;
      serialInfo.serialNo = e;
      serialInfo.sda = valSerialRes.ObjectData.sda;
      serialInfo.eda = valSerialRes.ObjectData.eda;
    }
  }

  // 先使用盘点单商品缓存数据验证商品是否存在
  let samegdsIndex = await searchFromOrigData(e);
  if (samegdsIndex > -1) {
    let currentGdsTemp = null;
    if (currentGdsPosition.value === 0)
      currentGdsTemp = Object.assign({}, dataList.value[samegdsIndex]);
    if (currentGdsPosition.value === 1)
      currentGdsTemp = Object.assign({}, inputData.value.details[samegdsIndex]);
    if (currentGdsPosition.value === 2)
      currentGdsTemp = Object.assign(
          inputData.value.details[samegdsIndex],
          {c_n: null, c_n_odd: null, c_n_pack: null, c_shelf_no: defaultShelfNo.value},
      );
    if (currentGdsPosition.value === 3)
      currentGdsTemp = Object.assign({}, barcodeList.value[samegdsIndex]);

    // 设置默认货架，及数量
    currentGdsTemp['_key'] = samegdsIndex;
    currentGdsTemp.c_first_dt = currentGdsTemp.c_first_dt
        ? currentGdsTemp.c_first_dt
        : dateRangUtil.getCurrentDateTime();
    // 分行累加模式下，时间为当前时间
    if (overwriteMode.value[0].value == '0') {
      currentGdsTemp.c_first_dt = dateRangUtil.getCurrentDateTime();
    }

    // 见物扫物模式，且设置了自动累加时
    if (isScan.value === true && isAutoAdd.value === true) {
      currentGdsTemp.c_n += 1;
    }

    let dev = '';
    // #ifdef APP-PLUS
    dev = plus.device.uuid; // 假设 `plus` 是全局对象
    // #endif
    currentGds.value = {
      ...currentGdsTemp,
      c_mk_userno: sUser,
      c_mk_dev: dev,
    };
    // 计数模式为累加时使用
    if (overwriteMode.value[0].value == '0') {
      currentGdsOrig.value = {
        ...currentGdsTemp,
        c_mk_userno: sUser,
        c_mk_dev: dev,
      }
      currentGds.value.c_n = null;
      currentGds.value.c_n_pack = null;
      currentGds.value.c_n_odd = null;
    }


    // 根据商品 称重/计件类型 c_plu_type === 1 称重PLU, 自动变成数量的录入方式
    const {c_n_pack, c_n_odd, c_pack, c_n, c_unit, c_plu_type} = currentGds.value;
    if (c_plu_type === '1') {
      // 先保留原录入方式
      inputModeOrig.value = [{
        ...inputMode.value[0]
      }]
      // 自动切换到数量录入方式
      toggleMode([{
        text:'数量',
        value: '1'
      }])
    }

    // 控制光标跳转
    setTimeout(() => {
      if (['1', '4'].includes(inputModeValue.value)) {
        if (isScan.value === true && isAutoAdd.value === true) {
          // 自动确认输入
          inputNumConfirm();
          // 如果是见物扫物模式下，且勾选了"自动追加"，光标回到扫商输入框
          RdsSearchBar?.value.clear();
        } else {
          gdsNumInput.value.getFocus();
        }
      } else {
        gdsNumPackInput.value.getFocus();
      }
    }, 100);

    // TODO: 保存本地持久化缓存
  }
};

// 根据商品编码或条码，返回商品所处的录入单位置
const searchFromOrigData = async (e) => {
  if (!e) {
    return -1;
  }
  // 定义索引数组
  const withShelfNoIndexes = [];
  const allIndexes = [];
  const barcodeIndexes = [];

  // currentGdsPosition:   0: dataList,  1: inputData.details， 2: inputData.details 但不匹配货架, 3:  多条码商品
  // 1. 在缓存数据中查找
  dataList.value.some((item, index) => {
    if (
        (item.c_shelf_no === defaultShelfNo.value && item.c_gcode === e) ||
        (item.c_shelf_no === defaultShelfNo.value && item.c_barcode === e)
    ) {
      withShelfNoIndexes.push(index);
    }
  });
  if (withShelfNoIndexes.length > 0) {
    currentGdsPosition.value = 0;
    let index = 0
    withShelfNoIndexes.forEach((item, _index) => {
      let gsort = dataList.value[item].c_gsort
      if ( gsort <= mySortMax.value && gsort > mySortMin.value) {
        index = _index
      }
    })
    return withShelfNoIndexes[index];
  }

  // 2. 在录入单数据中查找
  inputData.value.details.some((item, index) => {
    if (item.c_gcode === e || item.c_barcode === e) {
      allIndexes.push(index);
    }
    if (
        (item.c_shelf_no === defaultShelfNo.value && item.c_gcode === e) ||
        (item.c_shelf_no === defaultShelfNo.value && item.c_barcode === e)
    ) {
      withShelfNoIndexes.push(index);
    }
  });
  // 3. 在多条码商品中查找
  if (barcodeList.value.length > 0) {
    barcodeList.value.some((item, index) => {
      if (item.c_gcode === e || item.c_barcode === e) {
        barcodeIndexes.push(index);
      }
    });
  }
  if (barcodeIndexes.length > 0) {
    currentGdsPosition.value = 3; // 匹配多条码
    return barcodeIndexes[0];
  }
  if (withShelfNoIndexes.length > 0) {
    currentGdsPosition.value = 1; // 匹配货架
    let index = 0
    withShelfNoIndexes.forEach((item, _index) => {
      let gsort = inputData.value.details[item].c_gsort
      if ( gsort <= mySortMax.value && gsort > mySortMin.value) {
        index = _index
      }
    })
    return withShelfNoIndexes[index];
  }
  if (allIndexes.length > 0) {
    currentGdsPosition.value = 2; // 不匹配货架
    return allIndexes[0];
  }
  // 如果缓存数据不存在，调用服务验证商品是否存在
  if (e) {
    // 调用 ValidGdsInCount 验证商品
    let args = {
      c_count_id: inputData.value.main.c_count_id,
      c_gcode: e,
    };
    service.enjoyShowLoading('正在加载...');
    const res = await rdsRequestAsync(rdsUrl.scApi, '盘点录入单', 'ValidGdsInCount', args);
    service.enjoyHideLoading();
    const result = res.ObjectData
    if (!res.ObjectData || res.HasException) {
      uni.showToast({
        duration: 1000,
        icon: 'none',
        title: `${res.Exception.Message	}`,
        mask: true,
        complete: () => {
          onfocusGds();
        },
      });
      return -1;
    }

    if (result.gdsInfo) {
      barcodeList.value.push({
        ...result.gdsInfo,
        c_barcode: result.type === '条码' ? e : result.gdsInfo.c_barcode,
        c_pack: result.n,
        c_n: null,
        c_n_pack: null,
        c_n_odd: null,
      });
    }

    // 3. 匹配多条码商品中的数据
    if (barcodeList.value.length > 0) {
      barcodeList.value.some((item, index) => {
        if (item.c_gcode == e || item.c_barcode == e) {
          barcodeIndexes.push(index);
        }
      });
    }
    if (barcodeIndexes.length > 0) {
      currentGdsPosition.value = 3; // 匹配多条码
      return barcodeIndexes[0];
    }
  }

  uni.showToast({
    duration: 3500,
    icon: 'none',
    title: `【${e}】不在盘点范围！`,
    mask: true,
    complete: () => {
      currentGdsPosition.value = -1;
      onfocusGds();
    },
  });
  return -1;
};

// 获取系统配置
const getSysConfig = async () => {
  const c_step_list = await getDictList('复盘类型');
  c_step_list.forEach((item) => {
    sysConfig.value.c_step[item.c_id] = item.c_name;
  });

  const c_status_list = await getDictList('单据状态');
  c_status_list.forEach((e) => {
    sysConfig.value.c_status[e.c_id] = e.c_name;
  });

  const c_input_mode_list = await getDictList('盘点录入方式');
  c_input_mode_list.forEach((e) => {
    sysConfig.value.c_input_mode.push({
      text: e.c_name,
      value: e.c_id,
    });
  });

  weightUnits.value = await getWeightUnits();
  sysConfig.value.enableInputMode = await getRdsSysConfig('进销存管理参数', '盘点录入方式是否允许修改');
};

const getData = async (c_id) => {
  // 根据单据id获取盘点单明细
  const objectData = {
    BillId: c_id,
  };
  const result = await rdsRequest(rdsUrl.scApi, '商品盘点单', 'EnjoyBillQuery', objectData);
  origData.value.main = result.ds[0];
  origData.value.details = result.ds1;
};

const getInputList = async (c_id, c_store_id) => {
  const {loginInfo} = mainStore;
  // 获取盘点录入单列表
  const objectData = {
    IsNotPage: true,
    WhereList: [
      {
        c_col: 'c_count_id',
        c_oper: '等于',
        c_value: c_id,
        c_logic: '而且',
      },
      {
        c_col: 'c_store_id',
        c_oper: '等于',
        c_value: c_store_id,
        c_logic: '而且',
      },
      {
        c_col: 'c_status',
        c_oper: '等于',
        c_value: '0',
        c_logic: '而且',
      },
      {
        c_col: 'c_step',
        c_logic: '而且',
        c_oper: '等于',
        c_value: origData.value.main.c_progress, // 当前盘点进度 c_progress
      },
    ],
  };
  const result = await rdsRequest(rdsUrl.scApi, '盘点录入单', 'EnjoyQueryList', objectData);

  if (result.ReturnObject.length === 0) {
    // 创建盘点录入单
    await createCountInput(
        {
          bill_id: c_id,
          dept_level: '0',
          step: origData.value.main.c_progress,
          times: '1',
          device_no: loginInfo.sIMSI || '',
          rows_per_page: 0,
          login_store_id: c_store_id,
        },
        async (billId) => {
          c_id_ref.value = billId;
          await getInputData(billId);
        },
    );
  } else if (result.ReturnObject.length === 1) {
    const inputBillId = result.ReturnObject[0].c_id;
    await getInputData(inputBillId);
  }
};

const createCountInput = async (objectData, cb) => {
  uni.showModal({
    title: '提示',
    content: `创建盘点录入单?`,
    success: async (res) => {
      if (res.confirm) {
        service.enjoyShowLoading('正在加载...');
        const result = await rdsRequest(
            rdsUrl.scApi,
            '商品盘点单',
            'CreateCountInput',
            objectData,
            '761',
        );
        if (origData.value.main.c_mode2 == '3' && objectData.step == '1') {
          // 复盘方式为：AB盘时,创建A盘录入单后，自动创建B盘点录入单
          await rdsRequest(
              rdsUrl.scApi,
              '商品盘点单',
              'CreateCountInput',
              {
                ...objectData,
                step: '2',
              },
              '761',
          );
        }
        service.enjoyHideLoading();
        uni.showToast({
          duration: 3500,
          icon: 'none',
          title: `${result.msg}`,
          mask: true,
        });
        cb && (await cb(result.billId));
      }
    },
  });
};

const getInputData = async (c_id_param) => {
  c_id_ref.value = c_id_param;
  const {loginInfo} = mainStore;
  const objectData = {
    BillId: c_id_param,
  };
  const result = await rdsRequest(rdsUrl.scApi, '盘点录入单', 'EnjoyBillQuery', objectData);
  inputData.value.main = result.ds[0];
  inputData.value.details = result.ds1;

  // 按序号规则取当前用户的最大序号
  const formatUID = (num) => {
    let numStr = isNaN(Number(num)) ? '9999' : num.toString();
    if (numStr.length > 3) {
      // 如果数字长度大于3，则截取后三位
      return (numStr.substring(0,1) != '0' ? numStr.substring(0,1) : 1) + numStr.substring(numStr.length - 3);
    } else {
      // 如果数字长度小于3，则用0补足到3位
      return '1' + numStr.padStart(3, '0');
    }
  };

  mySortMin.value = Number(formatUID(loginInfo.sUser) + '00000');
  mySortMax.value = Number(formatUID(loginInfo.sUser) + '99999');

  let _myInputSort = []
  result.ds1.forEach((item) => {
    myInputSort.value = []
    if (item.c_gsort >= mySortMin.value && item.c_gsort <= mySortMax.value) {
      _myInputSort.push(item.c_gsort)
    }
  });
  myInputSort.value = [..._myInputSort]
  gsort.value = Math.max(0, ..._myInputSort, mySortMin.value) + 1;
};

const toggleScan = (value) => {
  isScan.value = value;
};

const toggleOverwriteMode = (value) => {
  overwriteMode.value = overwriteModeDict.value.filter(item => item.value == value);
}

const toggleModeRadio = (value) => {
  toggleMode(sysConfig.value.c_input_mode.filter((item) => item.value == value));
};

const toggleMode = (value) => {
  inputMode.value = value;
  if (value[0] && value[0].value == '4') {
    isScan.value = true;
  } else {
    isScan.value = false;
  }
};

const toggleAutoAdd = (value) => {
  isAutoAdd.value = value;
};

const clickScanRight = (type) => {
  uni.scanCode({
    success: (res) => {
      if (res.result) {
        if (type === 'defaultShelfNo') {
          defaultShelfNo.value = res.result;
        }
        if (type === 'defaultBarcode') {
          searchText.value = res.result;
          searchConfirm({'value': res.result});
        }
      }
    },
  });
};

const changeDefaultShelfNo = (e) => {
  const {value} = e;
  defaultShelfNo.value = `${value || '无货架'}`;
  setTimeout(() => {
    resetGds();
    RdsSearchBar.value?.clear();
  }, 100);
};

const saveCountInput = async () => {
  try {
    btnSaveEnabled.value = false;
    const inputDataMaxGsort = Math.max(0, ...myInputSort.value);

    const objectData = {
      NewList: [],
      ModifiedList: [inputData.value.main],
      DelList: [],
      TableName: 'tb_wo_count_input',
      PrimaryKeys: ['c_tenant_id', 'c_id'],
      BillSet: {
        BillIdKeyValue: {
          key: 'c_id',
          value: c_id_ref.value,
        },
        BillVariable: '',
        TableName: 'tb_wo_count_input',
        BillName: '盘点录入单',
      },
      ChildData: [
        {
          ChildTableName: 'tb_wo_count_input_g',
          ParentTableName: 'tb_wo_count_input',
          ChildColumnNames: ['c_id'],
          ParentColumnNames: ['c_id'],
          ChildSaveModel: {
            NewList: dataList.value.filter(
                (item) =>
                    item.c_gsort > inputDataMaxGsort &&
                    item.c_gsort >= mySortMin.value &&
                    item.c_gsort <= mySortMax.value,
            ),
            ModifiedList: dataList.value.filter(
                (item) =>
                    item.c_gsort <= inputDataMaxGsort ||
                    item.c_gsort > mySortMax.value ||
                    item.c_gsort < mySortMin.value,
            ),
            DelList: [],
            TableName: 'tb_wo_count_input_g',
            PrimaryKeys: ['c_tenant_id', 'c_id', 'c_gsort'],
          },
        },
      ],
    };

    service.enjoyShowLoading('正在加载...');
    const result = await rdsRequest(
        rdsUrl.scApi,
        '盘点录入单',
        'EnjoyBillSaveNew',
        objectData,
        '7C1',
    );
    if (result.BillId && !result.IsNewBillConflict) {
      uni.showToast({
        title: '保存成功',
        icon: 'success',
        mask: true,
        duration: 1500,
      })
    }
    await getInputData(inputData.value.main.c_id);
    canExit.value = true;
  } catch (error) {
    console.log(error);
  } finally {
    service.enjoyHideLoading();
    btnSaveEnabled.value = true;

    // 称重商品自动切换录入方式完成操作后切换回原录入方式
    setTimeout(() => {
      if (inputModeOrig.value.length > 0 && inputModeOrig.value[0].value != inputMode.value[0].value) {
        toggleMode([{
          ...inputModeOrig.value[0]
        }])
        inputModeOrig.value = []
      }
    }, 100);
    onfocusGds();
  }
};

const buttonClick = async (t) => {
  let { singleTag } = t;
  switch (singleTag) {
    case 'save':
      // 保存
      await saveCountInput();
      break;
    case 'default':
      changeToggle();
      break;
    default:
      break;
  }
};


const closeCallback = () => {
  onfocusGds();
};

const onfocusGds = () => {
  // 控制光标跳转
  setTimeout(() => {
    RdsSearchBar.value?.clear();
  }, 100);
};

const resetGds = () => {
  currentGds.value = {
    c_gcode: '',
    c_gname: '',
    c_pack: '',
    c_unit: '',
    c_n_pack: null,
    c_n_odd: null,
    c_n: null,
  };
};

const changeToggle = async () => {
  // 提示用户保存
  if (!canExit.value) {
    uni.showModal({
      title: '提示',
      content: '数据尚未保存，是否保存？',
      cancelText: '不保存',
      confirmText: '保存',
      success: async (res) => {
        if (res.confirm) {
          await saveCountInput();
          // 确定保存返回
          canExit.value = true;
          changeToggle();
        } else if (res.cancel) {
          // 不保存返回
          canExit.value = true;
          changeToggle();
        }
      },
    });
    return;
  }

  isToggle.value = !isToggle.value;
  if (inputData.value.main?.c_id) {
    // 加载当前用户录入的商品数据
    service.enjoyShowLoading('正在加载...');
    await getInputData(inputData.value.main.c_id);
    service.enjoyHideLoading();
    if ( isToggle.value && inputData.value.details.length > 0 ) {
      // 过滤当前用户数据
      dataList.value = inputData.value.details.filter(item => {
        return item.c_mk_userno == mainStore.loginInfo.sUser
      })
    }
  }
};

</script>

<style lang="scss" scoped>
@import '../../../main.scss';

.navigation {
  display: flex;
  height: 100vh;
  width: 100%;
  flex-direction: column;
  background: #F2F2F2;
}

.virtual_head,
.virtual_footer {
  display: flex;
  padding: 5px;
  margin: 0;
  background: #ffffff; //  #e9f7ff

  * {
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding: 0 2px;
    color: #505050 !important;
  }
}

.virtual_head {
  border-top: 1px solid #e5e5e5;
  border-bottom: 1px solid #e5e5e5;
  // border-bottom: 1px solid #ffffff;
}

.virtual_footer {
  justify-content: space-between;
  border-bottom: 1px solid #e5e5e5;
  border-top: 1px solid #e5e5e5;
  // border-top: 1px solid #ffffff;
}

.footer-view {
  width: 100%;
  flex: 1;
  ::v-deep .list_cell2 {
    margin: 0;
  }
}

.list_view {
  flex: 1;
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
}

.bottom-view {
  width: 100%;
  height: 100rpx;
  background: #FFFFFF;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  flex-direction: row;
}
.center-style {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  margin-right: 20rpx;
}
.gap-view {
  width: 20rpx;
  height: auto;
}

// 列表展示项自定义样式
.rds-count-input-content {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  background-color: #ffffff;
  //padding: $uni-spacing-row-base;
  //margin: $uni-spacing-row-base;
  margin: 0 20rpx 1rpx 20rpx;
  padding: 10rpx;
}

.rds-count-input-content:last-child {
  margin-bottom: 180rpx; // 保持和底部一定的距离
}

// 当前扫描到的商品
.with-current-gds {
  background-color: #fdffc2e0;
}

.input-item-index {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 0.2em 0 0;

  ::v-deep .m-text-id {
    color: #3a8ee6;
    font-size: 0.6em !important;
  }
}

.input-item-gdsinfo {
  display: flex;
  flex-direction: column;
  flex: 3;

  ::v-deep .m-text-title,
  ::v-deep .m-text-view {
    width: 12em;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.input-item-num {
  display: flex;
  justify-content: flex-start;
  flex: 2;
  flex-direction: column;

  * {
    margin: 0;
    padding: 0;
  }
}

// start 自定义更多按钮
.custom-box {
  display: flex;
  flex-direction: column;
}

.custom-menu {
  border-top: 0.03125rem solid #EEEEEE;
  display: flex;
  flex: 1 0 auto;
  width: 100%;
  //justify-content: flex-start;

  * {
    white-space: normal;
  }

  ::v-deep .m-card-input-content {
    display: block;
  }
}

::v-deep .m-card-input-view {
  border-bottom: none;
}

::v-deep .m-input-input {
  //border-bottom: 1px solid #cccccc;
  text-align: left !important;
}

//.setting-item {
//  display: inline-block;
//  align-items: center;
//  font-size: 0.8em;
//  margin: 0.5em;
//  padding: 0.5em;
//}
.setting-item {
  ::v-deep .m-card-input-view {
    display: inline-block;
    width: auto;
    padding-top: 0 !important;
  }
}

// #end 自定义更多按钮

.search_view {
  justify-content: space-between;
  display: flex;

  ::v-deep .main-seach-body {
    padding: 0;
  }

  .search_sno {
    flex: 0 0 40%;

    ::v-deep .uni-searchbar-content {
      padding-right: 0 !important;
    }
  }
}

.count_input_view {
  margin: 0 12rpx 10rpx;
  background-color: #FFFFFF;
  border-radius: 20rpx;
  position: relative;

  .count_input_column {
    padding: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .column_title {
    ::v-deep .m-input-input {
      font-size: 1rem;
      font-weight: bold;
      line-height: 1.5rem;
      span {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  .count_input_num {
    display: flex;

    ::v-deep .m-title-text {
      display: inline-block;
      min-width: 2rem;
    }
    ::v-deep .m-input-input {

    }
  }

  ::v-deep .uni-input-input {
    background:#F3F3F3;
  }

  ::v-deep .uni-input-input:disabled {
    background:#ccccc;
  }

  ::v-deep .m-card-input-view {
    align-items: stretch;
    align-items: center;
    height: 1rem!important;
    line-height: 1rem;
    background: none;
  }

  ::v-deep .m-card-input-title {
    // display: none;
    width: auto !important;

    span {
    }
  }

  ::v-deep .m-card-input-content {
    //width: 100%;
    //flex: 1;
    height: auto;
  }

  ::v-deep .m-card-input-right {
    display: none;
  }

  ::v-deep input {
    width: auto;
  }
}

.list_cell_item {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: stretch;
  align-content: flex-start;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;

  * {
    text-align: left;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.cell_color_code {
  text-align: left;
  color: #505050;
  font-size: 0.8rem;
}
.cell_color_code2 {
  text-align: left;
  color: #505050;
  font-size: 0.6rem;
}
.cell_color_id {
  padding-left: 0.4rem;
  text-align: left;
  font-size: 0.8rem;
  color: #3a8ee6;
}

.cell_color_num {
  padding-right: 1rem;
  text-align: right;
  color: #e64b3a;
}

.flex_w_auto {
  flex: 1 0 auto;
  // background: rgba(110, 180, 40, 1);
}

::v-deep .list_cell_even {
  /* 为偶数行设置样式 */
  background: #f2f2f2;
}

::v-deep .list_cell_odd {
  /* 为奇数行设置样式 */
  background: #ffffff;
}
</style>
